/**
 * 
 */
package com.ideazd.api.controller;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.common.reflect.TypeToken;
import com.ideazd.api.model.Cart;
import com.ideazd.api.model.CommodityCar;
import com.ideazd.api.model.CommodityVersion;
import com.ideazd.api.model.OrderDetails;
import com.ideazd.api.model.OrderSummary;
import com.ideazd.api.model.SentAddress;
import com.ideazd.api.model.SysAreas;
import com.ideazd.api.model.TransportationCost;
import com.ideazd.api.model.dto.RetDTO;
import com.ideazd.api.tools.DateUtil;
import com.ideazd.api.tools.SysUtil;
import com.ideazd.api.util.JsonUtil;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;

/**
 * @author yzz
 * @create 2016年5月16日 下午1:38:54
 */
@ControllerBind(controllerKey="buy")
public class BuyController extends Controller {
	private static final Logger log = Logger.getLogger(BuyController.class);
	
	/**
	 * 商品添加购物车
	 */
	@SuppressWarnings("null")
	public void addCart(){
		String commodityId = getPara("commodityId");
		String versionId = getPara("versionId");
		String useId = getPara("useId");
		Map<Object, Object> ret = new HashMap<Object,Object>();
		
		if(StrKit.isBlank(commodityId)||StrKit.isBlank(versionId)||StrKit.isBlank(useId)){
			ret.put("code","-2");
			ret.put("msg","必传参数不允许为空");
			renderJson(ret);
			return;
		}
		
		try {
			
			CommodityCar car = CommodityCar.dao.findFirst("select * from sta_commodity_car where useid = '"+useId+"' and versionid = '"+versionId+"' and commid = '"+commodityId+"'");
			
			if(null == car){
				car = new CommodityCar();
				car.set("id", SysUtil.getUUID());
				car.set("useid", useId);
				car.set("versionid", versionId);
				car.set("commid", commodityId);
				car.set("createdate", new Date());
				car.set("createid", useId);
				car.save();
				
			}
			
			ret.put("code","0");
			ret.put("msg","成功");
			
		} catch (Exception e) {
			ret.put("code","-1");
			ret.put("msg",e.getMessage());
		}
		
		renderJson(ret);
		return;
	}
	
	/**
	 * 获取购物车
	 */
	public void getCartList(){
		String useId = getPara("useId");
		Map<Object, Object> ret = new HashMap<Object,Object>();
		
		if(StrKit.isBlank(useId)){
			ret.put("code","-2");
			ret.put("msg","必传参数不允许为空");
			renderJson(ret);
			return;
		}
		
		try {
			
			List<CommodityCar> carts = CommodityCar.dao.find("select c.*,co.commodity_name,co.commodity_picture,v.version_type,v.version_stock,v.version_price from sta_commodity_car c left join sta_commodity co on c.commid = co.id left join sta_commodity_version v on v.id = c.versionid where c.useid = '"+useId+"' order by c.createdate desc");
			List<Map<Object, Object>> cartList = new ArrayList<Map<Object, Object>>();
			
			for(CommodityCar c:carts){
				Map<Object, Object> cart = new HashMap<Object,Object>();
				cart.put("cartId", c.get("id"));
				cart.put("commodityPicture", PropKit.get("server_uri") + c.get("commodity_picture"));
				cart.put("commodityName", c.get("commodity_name"));
				cart.put("commodityId", c.get("commid"));
				cart.put("versionId", c.get("versionid"));
				cart.put("versionName", c.get("version_type"));
				cart.put("versionStock", c.get("version_stock"));
				cart.put("versionPrice", c.get("version_price"));
				cartList.add(cart);
			}
			ret.put("data", cartList);
			ret.put("code","0");
			ret.put("msg","成功");
			
		} catch (Exception e) {
			ret.put("code","-1");
			ret.put("msg",e.getMessage());
		}
		
		renderJson(ret);
		return;
	}
	
	/**
    * 删除购物车
    */
	public void delCart(){
	   String cartId = getPara("cartId");
	   Map<Object,Object> ret = new HashMap<Object,Object>();
			
		try{
				
			if(StrKit.isBlank(cartId)){
				ret.put("code","-2");
				ret.put("msg","必传参数不允许为空");
				renderJson(ret);
				return;
			}
			
			if(!CommodityCar.dao.deleteById(cartId)){
				ret.put("code","-3");
				ret.put("msg","删除失败");
				renderJson(ret);
				return;
			}
			
			
			ret.put("code","0");
			ret.put("msg","删除成功");
		}catch(Exception e){
			ret.put("code","-1");
			ret.put("msg",e.getMessage());
		}
		renderJson(ret);
		return;
   }
	
	//运费
   public void getFreight(){
		String provinceCode =  getPara("provinceCode");
		RetDTO ret = new RetDTO();
		
		try{
			TransportationCost freight = TransportationCost.dao.findFirst("select * from sta_transportation_cost where provincecode = '"+provinceCode+"'");
			Map<Object,Object> freightMap = new HashMap<Object,Object>();
			
			if(null != freight){
				freightMap.put("freight", freight.get("cost"));
				ret.setData(freightMap);
				ret.setCode("0");
				ret.setMsg("获取成功");
			
			}else{
				TransportationCost defaultFreight = TransportationCost.dao.findFirst("select * from sta_transportation_cost where cosid = '3427dc37874a40e38f70f56e984471cs'");
				ret.setCode("0");
				ret.setMsg("获取成功");
				freightMap.put("freight", defaultFreight.get("cost"));
				ret.setData(freightMap);
			}
				
				
		}catch(Exception e){
			ret.setCode("-1");
			ret.setMsg(e.getMessage());
		}
		renderJson(ret);
		return;
	   
   }
   
   
   /**
    * 提交订单
    */
   @Before(Tx.class)
   public void postOrder(){
	   String useId = getPara("useId");
	   String postType = getPara("postType");
	   String addressId = getPara("addressId");
	   String freight = getPara("freight");
	   String data = getPara("data");
	   RetDTO ret = new RetDTO();
	   try{
		   
		   if(StrKit.isBlank(useId)||StrKit.isBlank(postType)||StrKit.isBlank(addressId)||StrKit.isBlank(freight)||StrKit.isBlank(data)){
				ret.setCode("-2");
				ret.setMsg("必传参数不允许为空");;
				renderJson(ret);
				return;
			}
			
			List<Cart> cartList = JsonUtil.fromJson(data, new TypeToken<ArrayList<Cart>>() {}.getType()); 
			String summaryId = SysUtil.getUUID();
		    Float summaryPrice =0f;
			
			for(Cart c:cartList){
				//Commodity commodity = Commodity.dao.findById(c.getCommodityId());
				CommodityVersion version = CommodityVersion.dao.findById(c.getVersionId());
				
				if(null == version){
					ret.setCode("-3");
					ret.setMsg(c.getVersionName()+"库存不足");
					renderJson(ret);
					return;
					
				}else{
					
					if(Integer.parseInt(c.getBuyNum()) > Integer.parseInt(version.get("version_stock").toString())){
						ret.setCode("-3");
						ret.setMsg(c.getVersionName()+"库存不足");
						renderJson(ret);
						return;
					}
				}
				
				
				
				//产品价格
				BigDecimal perPrice = new BigDecimal(version.get("version_price").toString());
				
				OrderDetails orderDetails = new OrderDetails();
				orderDetails.set("orddetid", SysUtil.getUUID());
				orderDetails.set("ordid", summaryId);
				orderDetails.set("commid", c.getCommodityId());
				orderDetails.set("commname", c.getCommodityName());
				orderDetails.set("commpic", c.getCommodityPicture());
				orderDetails.set("modid", c.getVersionId());
				orderDetails.set("modname", c.getVersionName());
				orderDetails.set("modprice", c.getVersionPrice());
				orderDetails.set("buynumber", c.getBuyNum());
				orderDetails.set("iscomment", 0);
				
				if(!orderDetails.save()){
					ret.setCode("-4");
					ret.setMsg("添加子订单失败");
					renderJson(ret);
					return;
				}
				
				summaryPrice += perPrice.multiply(new BigDecimal(c.getBuyNum())).floatValue();
				
				//删除购物车
				if("01".equals(postType)){
					String delSql = "delete from sta_commodity_car where id = '"+c.getCartId()+"'";
					
					if(Db.update(delSql) < 0){
						ret.setCode("-5");
						ret.setMsg("购物车删除失败");
						renderJson(ret);
						return;
					}
				}
				
			}
			String orderNo = DateUtil.formatDate(new Date(),"yyyyMMddHHmmssSSS");
			
			//地址
			SentAddress address = SentAddress.dao.findById(addressId);
			String province = SysAreas.dao.findById(address.get("provincecode")).getStr("area_name");
			String city = SysAreas.dao.findById(address.get("citycode")).getStr("area_name");
			String distrct = SysAreas.dao.findById(address.get("countycode")).getStr("area_name");
			
			OrderSummary orderSummary = new OrderSummary();
			orderSummary.set("ordid",summaryId);
			orderSummary.set("ordernumber",orderNo);
			orderSummary.set("useid", useId);
			orderSummary.set("totalprice",summaryPrice);
			orderSummary.set("commoditynumber",cartList.size());
			orderSummary.set("paystatus","01" );
			orderSummary.set("ordstate","01" );
			orderSummary.set("freight", freight);
			orderSummary.set("distribution", "1");
			orderSummary.set("takename", address.get("receivername"));
			orderSummary.set("takephone", address.get("telephone"));
			orderSummary.set("takeaddress", province+city+distrct+address.get("receiverstreet"));
			orderSummary.set("takezipcode", address.get("zipcode").toString());
			orderSummary.set("createtime", new Date());
			orderSummary.set("updateid", useId);
			orderSummary.set("updatename", "接口提交订单");
			orderSummary.set("updatedate", new Date());
			orderSummary.set("remarks", "提交订单");
			
			if(orderSummary.save()){
				ret.setCode("0");
				ret.setMsg("获取成功");
				Map<Object,Object> map = new HashMap<Object,Object>();
				map.put("orderNo", orderNo);
				ret.setData(map);
			}
			
			
			
		}catch(Exception e){
			ret.setCode("-1");
			ret.setMsg(e.getMessage());
			try {
				DbKit.getConfig().getConnection().rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		renderJson(ret);
		return;
   }
   
   
	
	
	
	
}
